import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Register from '../views/Register.vue'
import Login from '../views/Login.vue'
import Admin from '../views/Admin.vue'
import Error from '../views/404.vue'
import Home from '../components/Home.vue'
import User from '../components/User/User.vue'
import Roles from '../components/RightManagement/Roles.vue'
import Rights from '../components/RightManagement/Rights.vue'
import Cookies from 'js-cookie'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/admin',
    name: 'Admin',
    component: Admin,
    redirect:'/home',
    children: [
      { path: '/home', name: 'Home', component: Home },
      { path: '/users', name: 'User', component: User },
      { path: '/roles', name: 'Roles', component: Roles },
      { path: '/rights',name:'Rights',component:Rights }
    ]
  },
  // 404
  {
    path: '/error',
    component: Error
  },

  { path: '*', redirect: '/error' }
]

// const router = new VueRouter({
//   mode: 'history',
//   base: process.env.BASE_URL,
//   routes
// })

const createRouter = () => new VueRouter({
  mode: 'history', // require service support
  base: process.env.BASE_URL, // 配置基础地址
  routes
})

const router = createRouter()
 
// 重置路由配置，清空上一次路由配置
export function resetRouter() {
  const newRouter = createRouter()
  router.match = newRouter.match // reset router
}

// 添加路由守卫，实现权限控制
router.beforeEach((to, from, next) => {
  NProgress.start() // 开启进度条
  // 1.如果访问的是注册或者登录, 那么就放行
  if (to.path === '/login' || to.path === '/register' || to.path === '/error') {
    return next()
  }
  // 2.获取当前的登录状态
  // const token = sessionStorage.getItem('token')
  // 配合后端的要求, 后端无法从sessionStorage拿到token, 所以在后端设置了cookie, 前后端都可以拿到
  const token = Cookies.get('token')
  // 3.如果访问的是其它路由地址, 那么就需要判断是否已经登录
  //  如果已经登录, 那么就放行, 如果没有登录, 那么就强制跳转到登录界面
  if (token) {
    const routerRights = getRouterRights()
    const flag = isNext(routerRights, to.path)
    if (flag) {
      next() 
    } else {
      return next('/error')
    }
  } else {
    return next('/login')
  }
  NProgress.done() // 手动强制关闭一次  为了解决 手动切换地址时  进度条的不关闭的问题
})

// 后置守卫
router.afterEach(function() {
  NProgress.done() // 关闭进度条
})

const isNext = (routerRights: any, path: string) => {
  // console.log(routerRights.rightsPath,path);
  if (routerRights.rightsPath === path) return true
  if (routerRights.children) {
    for (let i = 0; i < routerRights.children.length; i++){
      const item = routerRights.children[i]
      // 利用递归套递归去实现路由权限的过滤
      if(isNext(item,path)) return true
    }
  }
  return false
}

// 得到当前用户路由权限
const getRouterRights = () => {
  const data: any = sessionStorage.getItem('userInfo') || []
  if (!data) return null
    const userInfo = JSON.parse(data)
    // console.log(userInfo);
    const routerRights = userInfo.rightsTree.filter((rights: any) => {
      // 将权限类型为 router 的都返回出来
      if(rights.rightsType === 'router') return rights
    })
    // console.log(roleRights);
    return routerRights[0]
 }

export default router
